package com.mjz.gui;

import com.mjz.dao.Database;

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CourseDialog extends JDialog {
    private JTextField courseNameField;
    private JComboBox<String> teacherComboBox;
    private JTextField maxStuNumField;
    private JTextField selectedNumField;
    private JTextField infoField;
    private JButton confirmButton;
    private final CourseManageFrame parent;

    public CourseDialog(CourseManageFrame parent, String title, boolean modal, JTable courseTable, int selectedRow) {
        super((JFrame) SwingUtilities.getWindowAncestor(parent), title, modal);
        this.parent = parent; // 持有父组件的引用
        setLayout(new GridBagLayout());
        setSize(400, 300);
        setLocationRelativeTo(parent);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 初始化各个组件
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(new JLabel("课程名称："), gbc);
        gbc.gridx = 1;
        courseNameField = new JTextField(20);
        add(courseNameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(new JLabel("教师姓名："), gbc);
        gbc.gridx = 1;
        teacherComboBox = new JComboBox<>();
        fillTeacherComboBox();
        add(teacherComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        add(new JLabel("最大人数："), gbc);
        gbc.gridx = 1;
        maxStuNumField = new JTextField(20);
        add(maxStuNumField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        add(new JLabel("已选人数："), gbc);
        gbc.gridx = 1;
        selectedNumField = new JTextField(20);
        add(selectedNumField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        add(new JLabel("信息："), gbc);
        gbc.gridx = 1;
        infoField = new JTextField(20);
        add(infoField, gbc);

        gbc.gridx = 1;
        gbc.gridy = 5;
        confirmButton = new JButton(selectedRow == -1 ? "确认添加" : "确认修改");
        add(confirmButton, gbc);

        if (selectedRow != -1) {
            populateFields(courseTable, selectedRow);
        }

        confirmButton.addActionListener(e -> {
            if (selectedRow == -1) {
                addCourseToDatabase();
            } else {
                modifyCourseInDatabase(courseTable, selectedRow);
            }
            parent.populateCourseTable((String)teacherComboBox.getSelectedItem()); // 更新特定教师的课程
            parent.updateTeacherComboBoxSelection((String)teacherComboBox.getSelectedItem()); // 更新教师下拉框选择
            dispose();
        });
    }

    private void fillTeacherComboBox() {
        try (Connection conn = Database.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT name FROM teacher")) {
            while (rs.next()) {
                teacherComboBox.addItem(rs.getString("name"));
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void populateFields(JTable courseTable, int row) {
        courseNameField.setText(courseTable.getValueAt(row, 1).toString());
        String teacherName = courseTable.getValueAt(row, 2).toString();
        teacherComboBox.setSelectedItem(teacherName); // 设置选中项为当前课程的教师
        maxStuNumField.setText(courseTable.getValueAt(row, 3).toString());
        selectedNumField.setText(courseTable.getValueAt(row, 4).toString());
        infoField.setText(courseTable.getValueAt(row, 5).toString());
    }

    private void addCourseToDatabase() {
        String name = courseNameField.getText();
        int tid = getTeacherId((String) teacherComboBox.getSelectedItem());
        int maxStuNum = Integer.parseInt(maxStuNumField.getText());
        int selectedNum = Integer.parseInt(selectedNumField.getText());
        String info = infoField.getText();

        String sql = "INSERT INTO course (name, tid, maxStuNum, selectedNum, info) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = Database.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, tid);
            pstmt.setInt(3, maxStuNum);
            pstmt.setInt(4, selectedNum);
            pstmt.setString(5, info);
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "课程添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void modifyCourseInDatabase(JTable courseTable, int row) {
        int courseId = (int) courseTable.getValueAt(row, 0);
        String name = courseNameField.getText();
        int tid = getTeacherId((String) teacherComboBox.getSelectedItem());
        int maxStuNum = Integer.parseInt(maxStuNumField.getText());
        int selectedNum = Integer.parseInt(selectedNumField.getText());
        String info = infoField.getText();

        String sql = "UPDATE course SET name = ?, tid = ?, maxStuNum = ?, selectedNum = ?, info = ? WHERE id = ?";
        try (Connection conn = Database.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, tid);
            pstmt.setInt(3, maxStuNum);
            pstmt.setInt(4, selectedNum);
            pstmt.setString(5, info);
            pstmt.setInt(6, courseId);
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "课程修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private int getTeacherId(String teacherName) {
        String sql = "SELECT id FROM teacher WHERE name = ?";
        try (Connection conn = Database.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, teacherName);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt("id");
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        return -1; // 未找到教师
    }
}